<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <!-- @tab-click="handleClick" -->
        <!-- tabs -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="role">
            <el-button type="primary" @click="showDialog=true"><i class="el-icon-plus" />新增角色</el-button>
            <!-- 表格 -->
            <el-table :data="list" style="margin: 20px 0;">
              <el-table-column label="序号" type="index" :index="indexMethod" />
              <el-table-column label="角色" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <!-- {{ row }} -->
                  <el-button size="mini" type="success" @click="assign(row.id)">分配权限</el-button>
                  <!-- @click="handleEdit(scope.$index, scope.row)"  -->
                  <el-button size="mini" type="primary" @click="edit(row.id)">编辑</el-button>
                  <!--  @click="handleDelete(scope.$index, scope.row)" -->
                  <el-button size="mini" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <div class="block">

              <el-pagination
                :current-page="page"
                :page-sizes="[1, 2, 3, 4,5]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="company">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <!-- 新增角色对话框 -->
        <el-dialog :title="showTitle" :visible="showDialog" @close="closeDialog">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="form.description" placeholder="请输入角色描述" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="showDialog = false">取 消</el-button>
            <el-button type="primary" @click="clickSubmit">确 定</el-button>
          </template>
        </el-dialog>

        <!-- 分配权限的弹层 -->
        <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">
          <el-tree
            ref="tree"
            node-key="id"
            :data="permissionList"
            :props="{label:'name'}"
            show-checkbox
            default-expand-all
            check-strictly
          />
          <template #footer>
            <div style="text-align: right;">
              <el-button @click="closeAssignDialog">取消</el-button>
              <el-button type="primary" @click="clickAssignSubmit">确定</el-button>
            </div>
          </template>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { reqAddRole, reqDelRole, reqGETRoleDetail, reqGetRoleList, reqUpdataRole } from '@/api/setting'
import { mapState } from 'vuex'
import { reqGetCompanyById } from '@/api/company'
import { reqGetPermissionList } from '@/api/permission'
import { transList2TreeData } from '@/utils'
import { reqAssignPerm } from '@/api/setting'
export default {
  name: 'Settings',
  data() {
    return {
      activeName: 'role',
      list: [],
      page: 1,
      pagesize: 3,
      total: 0,
      loading: false,
      showDialog: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ],
        description: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      permissionList: [],
      roleId: ''// 存储当前操作的角色id，将来拿着id发请求分配权限

    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    showTitle() {
      return this.form.id ? '编辑角色' : '新增角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompany()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { data: { total, rows }} = await reqGetRoleList(this.page, this.pagesize)
      console.log(total, rows, 5959595)
      this.list = rows
      this.total = total
      this.loading = false
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagesize = val
      // 每页条数变化后, 需要重置成第一页(规范)
      // 比如一共100条数据, 现在每页一条, 你现在可以在第80页,
      // 但是切换成每页100条后, 你只有1页, 只能在第1页!!
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.getRoleList()
    },

    indexMethod(index) {
      return index + 1 + this.pagesize * (this.page - 1)
    },

    del(id) {
      this.$confirm('该操作将永久删除该角色，继续么？', '提示', { type: 'warning' })
        .then(async() => {
          const res = await reqDelRole(id)
          console.log(res, 79797)
          this.$message.success(res.message)
          if (this.page > 1 && this.list.length === 1) {
            this.page--
          }
          this.getRoleList()
        })
        .catch(() => {
          this.$message.success('已取消该操作')
        })
    },

    closeDialog() {
      this.showDialog = false
      this.form = {
        name: '',
        description: ''
      }
    },

    clickSubmit() {
      let res
      this.$refs.form.validate(async(flag) => {
        if (!flag) return
        if (this.form.id) {
          res = await reqUpdataRole(this.form)
          console.log(res, 157)
          this.$message.success(res.message)
        } else {
          res = await reqAddRole(this.form)
          console.log(res, 144144)
          this.$message.success(res.message)
        }
      })

      this.showDialog = false
      this.getRoleList()
    },

    async edit(id) {
      const { data } = await reqGETRoleDetail(id)
      console.log(data, 154)
      this.showDialog = true
      this.form = data
    },

    async getCompany() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      console.log(data, 209209)
      this.companyForm = data
    },

    async assign(id) {
      this.showAssignDialog = true
      console.log(id)
      this.roleId = id
      // 1.获取所有权限列表
      const { data } = await reqGetPermissionList()
      // console.log(data, 2332333)
      // 列表数据=>树形数据
      this.permissionList = transList2TreeData(data, '0')
      // console.log(this.permissionList, 237237)

      // 2.获取这个角色之前的权限 进行回显
      const { data: { permIds }} = await reqGETRoleDetail(id)
      // permIds 角色之前的权限id组成的数组
      // 设置树形节点的选中 调用tree组件的方法
      this.$refs.tree.setCheckedKeys(permIds)
    },
    closeAssignDialog() {
      this.showAssignDialog = false
      // 关闭是，让树形节点都不选中
      this.$refs.tree.setCheckedKeys([])
    },
    async clickAssignSubmit() {
      // 获取树形节点的选中数组
      const permIds = this.$refs.tree.getCheckedKeys()
      console.log(permIds)
      const res = await reqAssignPerm(this.roleId, permIds)
      console.log(res, 268268)
      this.$message.success(res.message)
      this.closeAssignDialog()
    }

  }
}
</script>

<style>

</style>
